﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Core;
using Winter.Web.Mvc;
using Winter.Core.DAL;
using Winter.Core.Service;
using Winter.Core.Infrastructure.DependencyManagement;

namespace Winter.Web.mvc.Infrastructure
{
    internal class DependencyConfigure : IDependencyRegistrar
    {
        public static String GetConnectionString()
        {
            return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        }

        public static void Initialize()
        {
            var builder = new ContainerBuilder();
            //DependencyResolver.SetResolver( new Dependency(RegisterServices(builder)) );
            DependencyResolver.SetResolver(new Dependency());
        }

        private static IContainer RegisterServices(ContainerBuilder builder)
        {

            builder.RegisterAssemblyTypes( typeof(MvcApplication).Assembly).PropertiesAutowired();

            //deal with your dependencies here
            builder.Register<IDbContext>(c => new DataContext(GetConnectionString()));

            builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).PropertiesAutowired(PropertyWiringOptions.PreserveSetValues);

            builder.RegisterGeneric(typeof(GenericManager<,>)).As(typeof(IGenericManager<,>)).PropertiesAutowired(PropertyWiringOptions.PreserveSetValues);
            builder.RegisterType<ProductManager>().As<IProductManager>().PropertiesAutowired();


            return builder.Build();
        }



        public void Register(ContainerBuilder builder, Core.Infrastructure.ITypeFinder typeFinder)
        {
            builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly).PropertiesAutowired();

            //deal with your dependencies here
            builder.Register<IDbContext>(c => new DataContext(GetConnectionString()));

            builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>));//.PropertiesAutowired(PropertyWiringOptions.PreserveSetValues);

            builder.RegisterGeneric(typeof(GenericManager<,>)).As(typeof(IGenericManager<,>));//.PropertiesAutowired(PropertyWiringOptions.PreserveSetValues);
            builder.RegisterType<ProductManager>().As<IProductManager>().PropertiesAutowired();


        }

        public int Order
        {
            get { return 0; }
        }
    }
}